/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 *    Bagging.java
 *    Copyright (C) 1999 University of Waikato, Hamilton, New Zealand
 *
 */
package weka.classifiers.meta;

import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;

import weka.classifiers.RandomizableIteratedSingleClassifierEnhancer;
import weka.classifiers.trees.Grex;
import weka.core.AdditionalMeasureProducer;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.Randomizable;
import weka.core.RevisionUtils;
import weka.core.SelectedTag;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.WeightedInstancesHandler;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import wekaGrexBridge.WekaWrapper;

/**
<!-- globalinfo-start -->
 * Class for bagging a classifier to reduce variance. Can do classification and regression depending on the base learner. <br/>
 * <br/>
 * For more information, see<br/>
 * <br/>
 * Leo Breiman (1996). Bagging predictors. Machine Learning. 24(2):123-140.
 * <p/>
<!-- globalinfo-end -->
 *
<!-- technical-bibtex-start -->
 * BibTeX:
 * <pre>
 * &#64;article{Breiman1996,
 *    author = {Leo Breiman},
 *    journal = {Machine Learning},
 *    number = {2},
 *    pages = {123-140},
 *    title = {Bagging predictors},
 *    volume = {24},
 *    year = {1996}
 * }
 * </pre>
 * <p/>
<!-- technical-bibtex-end -->
 *
<!-- options-start -->
 * Valid options are: <p/>
 * 
 * <pre> -P
 *  Size of each bag, as a percentage of the
 *  training set size. (default 100)</pre>
 * 
 * <pre> -O
 *  Calculate the out of bag error.</pre>
 * 
 * <pre> -S &lt;num&gt;
 *  Random number seed.
 *  (default 1)</pre>
 * 
 * <pre> -I &lt;num&gt;
 *  Number of iterations.
 *  (default 10)</pre>
 * 
 * <pre> -D
 *  If set, classifier is run in debug mode and
 *  may output additional info to the console</pre>
 * 
 * <pre> -W
 *  Full name of base classifier.
 *  (default: weka.classifiers.trees.REPTree)</pre>
 * 
 * <pre> 
 * Options specific to classifier weka.classifiers.trees.REPTree:
 * </pre>
 * 
 * <pre> -M &lt;minimum number of instances&gt;
 *  Set minimum number of instances per leaf (default 2).</pre>
 * 
 * <pre> -V &lt;minimum variance for split&gt;
 *  Set minimum numeric class variance proportion
 *  of train variance for split (default 1e-3).</pre>
 * 
 * <pre> -N &lt;number of folds&gt;
 *  Number of folds for reduced error pruning (default 3).</pre>
 * 
 * <pre> -S &lt;seed&gt;
 *  Seed for random data shuffling (default 1).</pre>
 * 
 * <pre> -P
 *  No pruning.</pre>
 * 
 * <pre> -L
 *  Maximum tree depth (default -1, no maximum)</pre>
 * 
<!-- options-end -->
 *
 * Options after -- are passed to the designated classifier.<p>
 *
 * @author Eibe Frank (eibe@cs.waikato.ac.nz)
 * @author Len Trigg (len@reeltwo.com)
 * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
 * @version $Revision: 1.41 $
 */
public class BaggingGEMS
        extends RandomizableIteratedSingleClassifierEnhancer
        implements WeightedInstancesHandler, AdditionalMeasureProducer,
        TechnicalInformationHandler {

    /** for serialization */
    static final long serialVersionUID = -505879962237199703L;
    /** The size of each bag sample, as a percentage of the training size */
    protected int m_BagSizePercent = 100;
    /** Whether to calculate the out of bag error */
    protected boolean m_CalcOutOfBag = false;
    /** The out of bag error that has been calculated */
    protected double m_OutOfBagError;
    protected Grex m_GEMS;

    /**
     * Constructor.
     */
    public BaggingGEMS() throws Exception {
        m_GEMS = new Grex("GEMS");
        m_Classifier = new weka.classifiers.trees.REPTree();
    }

    /**
     * Returns a string describing classifier
     * @return a description suitable for
     * displaying in the explorer/experimenter gui
     */
    public String globalInfo() {

        return "Class for bagging a classifier to reduce variance. Can do classification " + "and regression depending on the base learner. \n\n" + "For more information, see\n\n" + getTechnicalInformation().toString();
    }

    /**
     * Returns an instance of a TechnicalInformation object, containing
     * detailed information about the technical background of this class,
     * e.g., paper reference or book this class is based on.
     *
     * @return the technical information about this class
     */
    public TechnicalInformation getTechnicalInformation() {
        TechnicalInformation result;

        result = new TechnicalInformation(Type.ARTICLE);
        result.setValue(Field.AUTHOR, "Leo Breiman");
        result.setValue(Field.YEAR, "1996");
        result.setValue(Field.TITLE, "Bagging predictors");
        result.setValue(Field.JOURNAL, "Machine Learning");
        result.setValue(Field.VOLUME, "24");
        result.setValue(Field.NUMBER, "2");
        result.setValue(Field.PAGES, "123-140");

        return result;
    }

    /**
     * String describing default classifier.
     *
     * @return the default classifier classname
     */
    protected String defaultClassifierString() {

        return "weka.classifiers.trees.REPTree";
    }

    /**
     * Returns an enumeration describing the available options.
     *
     * @return an enumeration of all the available options.
     */
    public Enumeration listOptions() {

        Vector newVector = new Vector(16);

        newVector.addElement(new Option(
                "\tSize of each bag, as a percentage of the\n" + "\ttraining set size. (default 100)",
                "P", 1, "-P"));
        newVector.addElement(new Option(
                "\tCalculate the out of bag error.",
                "O", 0, "-O"));


        newVector.addElement(new Option(
                "\tIf set, grex uses the given file name as bnf file.\n" + "\t[file name] (autogenerated)",
                "bnf", 1,
                "-bnf < name of BNF file, [file name] (autogenerated) >"));
        newVector.addElement(new Option(
                "\tIf set, grex is run the given number of generatiosns.\n" + "\t[>0]",
                "gen", 1, "-gen < number of generations, [>0] (1000) >"));
        newVector.addElement(new Option(
                "\tIf set, grex creates a population of the given size.\n" + "\t[>0]",
                "pop", 1, "-pop, < population size, [>0] (500) >"));
        newVector.addElement(new Option(
                "\tIf set, grex uses the given fraction as cross over \n" + "\trate. [0-1] (0.8)",
                "cro", 1, "-cro < crossover rate, [0-1] (0.8) >"));
        newVector.addElement(new Option(
                "\tIf set, grex uses the given fraction as mutaion rate.\n" + "\t[0-1]",
                "mut", 1, "-mut < mutation rate, [0-1] (0.0001) >"));
        newVector.addElement(new Option(
                "\tIf set, grex uses the given number as max creation depth.\n" + "\t[>0]",
                "crd", 1, "-crd < creation depth, [>0] (6) >"));
        newVector.addElement(new Option(
                "\tIf set, grex uses the given number as length factor.\n" + "\t[>0]",
                "len", 1, "-len < length factor, [>0] (0.01) >"));
        newVector.addElement(new Option(
                "\tIf set, grex uses the simplification. (false)",
                "sim", 0, "-sim"));
        newVector.addElement(new Option(
                "\tIf set, grex uses the given algorithm as creation\n" + "\talgorithm. [RAMPED_H&H = 0, GROW = 1, VARIABLE = 2] (0)",
                "crt", 1,
                "-crt < creation function, [RAMPED_H&H = 0, GROW = 1, VARIABLE = 2] (0) >"));
        newVector.addElement(new Option(
                "\tIf set, grex uses elitism, i.e. the best gene survives\n" + "\tto the next generation. (true)",
                "eli", 0, "-eli"));
        newVector.addElement(new Option(
                "\tIf set, grex uses stops if no change in fitness for the\n" + "\tgiven number of generations. [0>] (100)",
                "per", 1, "-per < number of generations without changes to run before stopping, [0>] (100) >"));
        newVector.addElement(new Option(
                "\tIf set, grex is run bat number of batches. The best GP in the winning batch is returned \n" + "\t[>0] (1)",
                "bat", 1, "-bat < number of batches, [>0] (1) >"));
        Enumeration enu = super.listOptions();
        while (enu.hasMoreElements()) {
            newVector.addElement(enu.nextElement());
        }
        return newVector.elements();
    }

    /**
     * Parses a given list of options. <p/>
     *
    <!-- options-start -->
     * Valid options are: <p/>
     *
     * <pre> -P
     *  Size of each bag, as a percentage of the
     *  training set size. (default 100)</pre>
     *
     * <pre> -O
     *  Calculate the out of bag error.</pre>
     *
     * <pre> -S &lt;num&gt;
     *  Random number seed.
     *  (default 1)</pre>
     *
     * <pre> -I &lt;num&gt;
     *  Number of iterations.
     *  (default 10)</pre>
     *
     * <pre> -D
     *  If set, classifier is run in debug mode and
     *  may output additional info to the console</pre>
     *
     * <pre> -W
     *  Full name of base classifier.
     *  (default: weka.classifiers.trees.REPTree)</pre>
     *
     * <pre>
     * Options specific to classifier weka.classifiers.trees.REPTree:
     * </pre>
     *
     * <pre> -M &lt;minimum number of instances&gt;
     *  Set minimum number of instances per leaf (default 2).</pre>
     *
     * <pre> -V &lt;minimum variance for split&gt;
     *  Set minimum numeric class variance proportion
     *  of train variance for split (default 1e-3).</pre>
     *
     * <pre> -N &lt;number of folds&gt;
     *  Number of folds for reduced error pruning (default 3).</pre>
     *
     * <pre> -S &lt;seed&gt;
     *  Seed for random data shuffling (default 1).</pre>
     *
     * <pre> -P
     *  No pruning.</pre>
     *
     * <pre> -L
     *  Maximum tree depth (default -1, no maximum)</pre>
     *
    <!-- options-end -->
     *
     * Options after -- are passed to the designated classifier.<p>
     *
     * @param options the list of options as an array of strings
     * @throws Exception if an option is not supported
     */
    public void setOptions(String[] options) throws Exception {

        String bagSize = Utils.getOption('P', options);
        if (bagSize.length() != 0) {
            setBagSizePercent(Integer.parseInt(bagSize));
        } else {
            setBagSizePercent(100);
        }

        setCalcOutOfBag(Utils.getFlag('O', options));


        String tmp = Utils.getOption("bnf", options);
        if (tmp.length() != 0) {
            m_GEMS.setBNF_File(
                    new SelectedTag(Integer.parseInt(tmp), Grex.TAGS_BNF));
        } else {
            m_GEMS.setBNF_File(
                    new SelectedTag(m_GEMS.m_BNF, Grex.TAGS_BNF));
        }

        tmp = Utils.getOption("fit", options);
        if (tmp.length() != 0) {
            m_GEMS.setFitness(
                    new SelectedTag(Integer.parseInt(tmp), Grex.updateTAGS_Fitness()));
        } else {
            m_GEMS.setFitness(
                    new SelectedTag(m_GEMS.m_Fitness, Grex.updateTAGS_Fitness()));
        }

        tmp = Utils.getOption("gen", options);
        if (tmp.length() != 0) {
            m_GEMS.setGenerations(Integer.parseInt(tmp));
        }

        tmp = Utils.getOption("pop", options);
        if (tmp.length() != 0) {
            m_GEMS.setPopulationSize(Integer.parseInt(tmp));
        }

        tmp = Utils.getOption("cro", options);
        if (tmp.length() != 0) {
            m_GEMS.setCrossoverProbability(Double.parseDouble(tmp));
        }

        tmp = Utils.getOption("mut", options);
        if (tmp.length() != 0) {
            m_GEMS.setMutationProbability(Double.parseDouble(tmp));
        }

        tmp = Utils.getOption("crd", options);
        if (tmp.length() != 0) {
            m_GEMS.setCreationDepth(Integer.parseInt(tmp));
        }

        tmp = Utils.getOption("len", options);
        if (tmp.length() != 0) {
            m_GEMS.setLengthFactor(Double.parseDouble(tmp));
        }

        tmp = Utils.getOption("bat", options);
        if (tmp.length() != 0) {
            m_GEMS.setNumberOfBatches(Integer.parseInt(tmp));
        }

        m_GEMS.setSimplify(Utils.getFlag("sim", options));

        tmp = Utils.getOption("crt", options);
        if (tmp.length() != 0) {
            m_GEMS.setCreationType(
                    new SelectedTag(Integer.parseInt(tmp), Grex.TAGS_crt));
        } else {
            m_GEMS.setCreationType(
                    new SelectedTag(m_GEMS.m_crt, Grex.TAGS_crt));
        }

        m_GEMS.setElitism(Utils.getFlag("eli", options));

        tmp = Utils.getOption("per", options);
        if (tmp.length() != 0) {
            m_GEMS.setStopWithoutImprovement(Integer.parseInt(tmp));
        }

        super.setOptions(options);
    }

    /**
     * Gets the current settings of the Classifier.
     *
     * @return an array of strings suitable for passing to setOptions
     */
    public String[] getOptions() {


        String[] superOptions = super.getOptions();
        String[] options = new String[superOptions.length + 27];

        int current = 0;
        options[current++] = "-P";
        options[current++] = "" + getBagSizePercent();

        if (getCalcOutOfBag()) {
            options[current++] = "-O";
        }


        options[current++] = "-bnf";
        options[current++] = "" + m_GEMS.m_BNF;
        options[current++] = "-fit";
        options[current++] = "" + m_GEMS.m_Fitness;
        options[current++] = "-gen";
        options[current++] = "" + m_GEMS.getGenerations();
        options[current++] = "-pop";
        options[current++] = "" + m_GEMS.getPopulationSize();
        options[current++] = "-cro";
        options[current++] = "" + m_GEMS.getCrossoverProbability();
        options[current++] = "-mut";
        options[current++] = "" + m_GEMS.getMutationProbability();
        options[current++] = "-crd";
        options[current++] = "" + m_GEMS.getCreationDepth();
        options[current++] = "-len";
        options[current++] = "" + m_GEMS.getLengthFactor();
        options[current++] = "-bat";
        options[current++] = "" + m_GEMS.getNumberOfBatches();
        if (m_GEMS.getSimplify()) {
            options[current++] = "-sim";
        }
        options[current++] = "-crt";
        options[current++] = "" + m_GEMS.m_crt;
        if (m_GEMS.getElitism()) {
            options[current++] = "-eli";
        }
        options[current++] = "-per";
        options[current++] = "" + m_GEMS.getStopWithoutImprovement();

        System.arraycopy(superOptions, 0, options, current,
                superOptions.length);

        current += superOptions.length;
        while (current < options.length) {
            options[current++] = "";
        }
        return options;
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String bagSizePercentTipText() {
        return "Size of each bag, as a percentage of the training set size.";
    }

    /**
     * Gets the size of each bag, as a percentage of the training set size.
     *
     * @return the bag size, as a percentage.
     */
    public int getBagSizePercent() {

        return m_BagSizePercent;
    }

    /**
     * Sets the size of each bag, as a percentage of the training set size.
     *
     * @param newBagSizePercent the bag size, as a percentage.
     */
    public void setBagSizePercent(int newBagSizePercent) {

        m_BagSizePercent = newBagSizePercent;
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String calcOutOfBagTipText() {
        return "Whether the out-of-bag error is calculated.";
    }

    /**
     * Set whether the out of bag error is calculated.
     *
     * @param calcOutOfBag whether to calculate the out of bag error
     */
    public void setCalcOutOfBag(boolean calcOutOfBag) {

        m_CalcOutOfBag = calcOutOfBag;
    }

    /**
     * Get whether the out of bag error is calculated.
     *
     * @return whether the out of bag error is calculated
     */
    public boolean getCalcOutOfBag() {

        return m_CalcOutOfBag;
    }

    /**
     * Gets the out of bag error that was calculated as the classifier
     * was built.
     *
     * @return the out of bag error
     */
    public double measureOutOfBagError() {

        return m_OutOfBagError;
    }

    /**
     * Returns an enumeration of the additional measure names.
     *
     * @return an enumeration of the measure names
     */
    public Enumeration enumerateMeasures() {

        Vector newVector = new Vector(1);
        newVector.addElement("measureOutOfBagError");
        return newVector.elements();
    }

    /**
     * Returns the value of the named measure.
     *
     * @param additionalMeasureName the name of the measure to query for its value
     * @return the value of the named measure
     * @throws IllegalArgumentException if the named measure is not supported
     */
    public double getMeasure(String additionalMeasureName) {

        if (additionalMeasureName.equalsIgnoreCase("measureOutOfBagError")) {
            return measureOutOfBagError();
        } else {
            throw new IllegalArgumentException(additionalMeasureName + " not supported (Bagging)");
        }
    }

    /**
     * Creates a new dataset of the same size using random sampling
     * with replacement according to the given weight vector. The
     * weights of the instances in the new dataset are set to one.
     * The length of the weight vector has to be the same as the
     * number of instances in the dataset, and all weights have to
     * be positive.
     *
     * @param data the data to be sampled from
     * @param random a random number generator
     * @param sampled indicating which instance has been sampled
     * @return the new dataset
     * @throws IllegalArgumentException if the weights array is of the wrong
     * length or contains negative weights.
     */
    public final Instances resampleWithWeights(Instances data,
            Random random,
            boolean[] sampled) {

        double[] weights = new double[data.numInstances()];
        for (int i = 0; i < weights.length; i++) {
            weights[i] = data.instance(i).weight();
        }
        Instances newData = new Instances(data, data.numInstances());
        if (data.numInstances() == 0) {
            return newData;
        }
        double[] probabilities = new double[data.numInstances()];
        double sumProbs = 0, sumOfWeights = Utils.sum(weights);
        for (int i = 0; i < data.numInstances(); i++) {
            sumProbs += random.nextDouble();
            probabilities[i] = sumProbs;
        }
        Utils.normalize(probabilities, sumProbs / sumOfWeights);

        // Make sure that rounding errors don't mess things up
        probabilities[data.numInstances() - 1] = sumOfWeights;
        int k = 0;
        int l = 0;
        sumProbs = 0;
        while ((k < data.numInstances() && (l < data.numInstances()))) {
            if (weights[l] < 0) {
                throw new IllegalArgumentException("Weights have to be positive.");
            }
            sumProbs += weights[l];
            while ((k < data.numInstances()) &&
                    (probabilities[k] <= sumProbs)) {
                newData.add(data.instance(l));
                sampled[l] = true;
                newData.instance(k).setWeight(1);
                k++;
            }
            l++;
        }
        return newData;
    }

    public void buildEnsemble(Instances data) throws Exception {

        // can classifier handle the data?
        getCapabilities().testWithFail(data);

        // remove instances with missing class
        data = new Instances(data);
        data.deleteWithMissingClass();

        super.buildClassifier(data);

        if (m_CalcOutOfBag && (m_BagSizePercent != 100)) {
            throw new IllegalArgumentException("Bag size needs to be 100% if " +
                    "out-of-bag error is to be calculated!");
        }

        int bagSize = data.numInstances() * m_BagSizePercent / 100;
        Random random = new Random(m_Seed);

        boolean[][] inBag = null;
        if (m_CalcOutOfBag) {
            inBag = new boolean[m_Classifiers.length][];
        }

        for (int j = 0; j < m_Classifiers.length; j++) {
            Instances bagData = null;

            // create the in-bag dataset
            if (m_CalcOutOfBag) {
                inBag[j] = new boolean[data.numInstances()];
                bagData = resampleWithWeights(data, random, inBag[j]);
            } else {
                bagData = data.resampleWithWeights(random);
                if (bagSize < data.numInstances()) {
                    bagData.randomize(random);
                    Instances newBagData = new Instances(bagData, 0, bagSize);
                    bagData = newBagData;
                }
            }

            if (m_Classifier instanceof Randomizable) {
                ((Randomizable) m_Classifiers[j]).setSeed(random.nextInt());
            }

            // build the classifier
            m_Classifiers[j].buildClassifier(bagData);
        }

        // calc OOB error?
        if (getCalcOutOfBag()) {
            double outOfBagCount = 0.0;
            double errorSum = 0.0;
            boolean numeric = data.classAttribute().isNumeric();

            for (int i = 0; i < data.numInstances(); i++) {
                double vote;
                double[] votes;
                if (numeric) {
                    votes = new double[1];
                } else {
                    votes = new double[data.numClasses()];
                }

                // determine predictions for instance
                int voteCount = 0;
                for (int j = 0; j < m_Classifiers.length; j++) {
                    if (inBag[j][i]) {
                        continue;
                    }

                    voteCount++;
                    double pred = m_Classifiers[j].classifyInstance(data.instance(i));
                    if (numeric) {
                        votes[0] += pred;
                    } else {
                        votes[(int) pred]++;
                    }
                }

                // "vote"
                if (numeric) {
                    vote = votes[0];
                    if (voteCount > 0) {
                        vote /= voteCount;    // average
                    }
                } else {
                    vote = Utils.maxIndex(votes);   // majority vote
                }

                // error for instance
                outOfBagCount += data.instance(i).weight();
                if (numeric) {
                    errorSum += StrictMath.abs(vote - data.instance(i).classValue()) * data.instance(i).weight();
                } else {
                    if (vote != data.instance(i).classValue()) {
                        errorSum += data.instance(i).weight();
                    }
                }
            }

            m_OutOfBagError = errorSum / outOfBagCount;
        } else {
            m_OutOfBagError = 0;
        }
    }

    /**
     * Bagging method.
     *
     * @param data the training data to be used for generating the
     * bagged classifier.
     * @throws Exception if the classifier could not be built successfully
     */
    public void buildClassifier(Instances data) throws Exception {
        buildEnsemble(data);
        int firstModel = data.numAttributes() - 1, column = firstModel;
        Instances gemsData = new Instances(data);
        for (int j = 0; j < m_Classifiers.length; j++) {
            for (int i = 0; i < gemsData.numClasses(); i++) {
                gemsData.insertAttributeAt(new Attribute("model_" + j + "_" + i), column++);
            }
        }
        for (int i = 0; i < data.numInstances(); i++) {
            column = firstModel;
            for (int j = 0; j < m_Classifiers.length; j++) {
                double[] pred = m_Classifiers[j].distributionForInstance(data.instance(i));
                for (int n = 0; n < gemsData.numClasses(); n++) {
                    gemsData.instance(i).setValue(column++, pred[n]);
                }
            }
        }


        m_GEMS.setFirstANN(firstModel);
        if (m_CalcOutOfBag) {
            int numBatches = getNumberOfBatches();
            setNumberOfBatches(1);
            if (m_CalcOutOfBag && (m_BagSizePercent != 100)) {
                throw new IllegalArgumentException("Bag size needs to be 100% if " +
                        "out-of-bag error is to be calculated!");
            }

            int bagSize = gemsData.numInstances() * m_BagSizePercent / 100;
            Random random = new Random(m_Seed);

            boolean[][] inBag = null;
            inBag = new boolean[numBatches][];

            boolean numeric = gemsData.classAttribute().isNumeric();
            double oobError;
            double minError = Double.MAX_VALUE;
            WekaWrapper bestGEMS = null;
            for (int j = 0; j < numBatches; j++) {
                Instances bagData = null;

                // create the in-bag dataset
                inBag[j] = new boolean[gemsData.numInstances()];
                bagData = resampleWithWeights(gemsData, random, inBag[j]);

                // build the classifier
                m_GEMS.buildClassifier(bagData);

                // calc OOB error?
                double outOfBagCount = 0.0;
                double errorSum = 0.0;

                // determine predictions for instance
                for (int i = 0; i < gemsData.numInstances(); i++) {
                    if (inBag[j][i]) {
                        continue;
                    }

                    double pred = m_GEMS.classifyInstance(gemsData.instance(i));
                    // error for instance
                    outOfBagCount += gemsData.instance(i).weight();
                    if (numeric) {
                        errorSum += StrictMath.abs(pred - gemsData.instance(i).classValue()) * data.instance(i).weight();
                    } else {
                        if (pred != gemsData.instance(i).classValue()) {
                            errorSum += gemsData.instance(i).weight();
                        }
                    }
                }
                oobError = errorSum / outOfBagCount;
                if (oobError < minError) {
                    minError = oobError;
                    bestGEMS = m_GEMS.getModel();
                }
            }
            m_GEMS.setModel(bestGEMS);
            setNumberOfBatches(numBatches);
        } else {
            m_GEMS.buildClassifier(gemsData);
        }
    }

    /**
     * Calculates the class membership probabilities for the given test
     * instance.
     *
     * @param instance the instance to be classified
     * @return preedicted class probability distribution
     * @throws Exception if distribution can't be computed successfully
     */
    public double[] distributionForInstance(Instance instance) throws Exception {

        /*double[] sums = new double[instance.numClasses()], newProbs;

        for (int i = 0; i < m_NumIterations; i++) {
        if (instance.classAttribute().isNumeric() == true) {
        sums[0] += m_Classifiers[i].classifyInstance(instance);
        } else {
        newProbs = m_Classifiers[i].distributionForInstance(instance);
        for (int j = 0; j < newProbs.length; j++) {
        sums[j] += newProbs[j];
        }
        }
        }
        if (instance.classAttribute().isNumeric() == true) {
        sums[0] /= (double) m_NumIterations;
        return sums;
        } else if (Utils.eq(Utils.sum(sums), 0)) {
        return sums;
        } else {
        Utils.normalize(sums);
        return sums;
        }*/
        int firstModel = instance.dataset().numAttributes() - 1, column = firstModel;
        Instances data = new Instances(instance.dataset());
        for (int j = 0; j < m_Classifiers.length; j++) {
            for (int i = 0; i < instance.dataset().numClasses(); i++) {
                data.insertAttributeAt(new Attribute("model_" + j + "_" + i), column++);
            }
        }
        data.setClassIndex(data.numAttributes() - 1);
        Instance newInstance = new DenseInstance(data.numAttributes());
        for (int i = 0; i < instance.numAttributes(); i++) {
            newInstance.setValue(i, instance.value(i));
        }
        column = firstModel;
        for (int j = 0; j < m_Classifiers.length; j++) {
            double[] pred = m_Classifiers[j].distributionForInstance(instance);
            for (int n = 0; n < instance.numClasses(); n++) {
                newInstance.setValue(column++, pred[n]);
            }
        }
        return m_GEMS.distributionForInstance(newInstance);
    }

    /**
     * Returns description of the bagged classifier.
     *
     * @return description of the bagged classifier as a string
     */
    public String toString() {

        if (m_Classifiers == null) {
            return "Bagging: No model built yet.";
        }
        StringBuffer text = new StringBuffer();
        text.append("All the base classifiers: \n\n");
        for (int i = 0; i < m_Classifiers.length; i++) {
            text.append(m_Classifiers[i].toString() + "\n\n");
        }

        if (m_CalcOutOfBag) {
            text.append("Out of bag error: " + Utils.doubleToString(m_OutOfBagError, 4) + "\n\n");
        }

        return text.toString();
    }

    /**
     * Returns the revision string.
     *
     * @return		the revision
     */
    public String getRevision() {
        return RevisionUtils.extract("$Revision: 1.41 $");
    }

    /**
     * Main method for testing this class.
     *
     * @param argv the options
     */
    public static void main(String[] argv) throws Exception {
        runClassifier(new BaggingGEMS(), argv);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String crossoverProbabilityTipText() {
        return "The crossover probability used.";
    }

    /**
     * Get the value of cro.
     *
     * @return Value of cro.
     */
    public double getCrossoverProbability() {

        return m_GEMS.getCrossoverProbability();
    }

    /**
     * Set the value of cro.
     *
     * @param crossoverProbability Value to assign to cro.
     */
    public void setCrossoverProbability(double crossoverProbability) {

        m_GEMS.setCrossoverProbability(crossoverProbability);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String mutationProbabilityTipText() {
        return "The mutation probability used.";
    }

    /**
     * Get the value of mut.
     *
     * @return Value of mut.
     */
    public double getMutationProbability() {

        return m_GEMS.getMutationProbability();
    }

    /**
     * Set the value of mut.
     *
     * @param mutationProbability Value to assign to mut.
     */
    public void setMutationProbability(double mutationProbability) {

        m_GEMS.setMutationProbability(mutationProbability);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String lengthFactorTipText() {
        return "The length factor to be used as a means of controlling the complexity of the classifier.";
    }

    /**
     * Get the value of len.
     *
     * @return Value of len.
     */
    public double getLengthFactor() {

        return m_GEMS.getLengthFactor();
    }

    /**
     * Set the value of len.
     *
     * @param lengthFactor Value to assign to len.
     */
    public void setLengthFactor(double lengthFactor) {

        m_GEMS.setLengthFactor(lengthFactor);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String BNF_FileTipText() {
        return "The BNF file to use.";
    }

    /**
     * Get the value of
     *
     * @return Value of Settings.
     */
    public SelectedTag getBNF_File() {
        return m_GEMS.getBNF_File();
    }

    /**
     * Set the value of Settings.
     *
     * @param bnfFile Value to assign to Settings.
     */
    public void setBNF_File(SelectedTag value) {
        m_GEMS.setBNF_File(value);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String FitnessTipText() {
        return "The Fitness function to use.";
    }

    /**
     * Get the value of
     *
     * @return Value of Settings.
     */
    public SelectedTag getFitness() {
        return m_GEMS.getFitness();
    }

    /**
     * Set the value of Settings.
     *
     * @param Fitness Value to assign to Settings.
     */
    public void setFitness(SelectedTag value) {
        m_GEMS.setFitness(value);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String generationsTipText() {
        return "The number of generations to run.";
    }

    /**
     * Get the value of gen.
     *
     * @return Value of gen.
     */
    public int getGenerations() {

        return m_GEMS.getGenerations();
    }

    /**
     * Set the value of gen.
     *
     * @param generations Value to assign to gen.
     */
    public void setGenerations(int generations) {

        m_GEMS.setGenerations(generations);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String populationSizeTipText() {
        return "The size of the population.";
    }

    /**
     * Get the value of pop.
     *
     * @return Value of pop.
     */
    public int getPopulationSize() {

        return m_GEMS.getPopulationSize();
    }

    /**
     * Set the value of pop.
     *
     * @param populationSize Value to assign to pop.
     */
    public void setPopulationSize(int populationSize) {

        m_GEMS.setPopulationSize(populationSize);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String creationDepthTipText() {
        return "The maximum creation depth of generated genes.";
    }

    /**
     * Get the value of crd.
     *
     * @return Value of crd.
     */
    public int getCreationDepth() {

        return m_GEMS.getCreationDepth();
    }

    /**
     * Set the value of crd.
     *
     * @param creationDepth Value to assign to crd.
     */
    public void setCreationDepth(int creationDepth) {

        m_GEMS.setCreationDepth(creationDepth);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String creationTypeTipText() {
        return "The creation strategy to use. [RAMPED_H&H = 0, GROW = 1, VARIABLE = 2]";
    }

    /**
     * Get the value of crt.
     *
     * @return Value of crt.
     */
    public SelectedTag getCreationType() {

        return m_GEMS.getCreationType();
    }

    /**
     * Set the value of crt.
     *
     * @param creationType Value to assign to crt.
     */
    public void setCreationType(SelectedTag value) {
        m_GEMS.setCreationType(value);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String stopWithoutImprovementTipText() {
        return "The maximum generations to continue running without improvement. Also called percistence";
    }

    /**
     * Get the value of per.
     *
     * @return Value of per.
     */
    public int getStopWithoutImprovement() {

        return m_GEMS.getStopWithoutImprovement();
    }

    /**
     * Set the value of per.
     *
     * @param stopWithoutImprovement Value to assign to per.
     */
    public void setStopWithoutImprovement(int stopWithoutImprovement) {

        m_GEMS.setStopWithoutImprovement(stopWithoutImprovement);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String numberOfBatchesTipText() {
        return "The number of batches to run";
    }

    /**
     * Get the value of bat.
     *
     * @return Value of bat.
     */
    public int getNumberOfBatches() {

        return m_GEMS.getNumberOfBatches();
    }

    /**
     * Set the value of bat.
     *
     * @param numberOfBatches Value to assign to bat.
     */
    public void setNumberOfBatches(int numberOfBatches) {

        m_GEMS.setNumberOfBatches(numberOfBatches);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String simplifyTipText() {
        return "Try to simplify the final rule?";
    }

    /**
     * Get the value of sim.
     *
     * @return Value of sim.
     */
    public boolean getSimplify() {

        return m_GEMS.getSimplify();
    }

    /**
     * Set the value of sim.
     *
     * @param simplify Value to assign to sim.
     */
    public void setSimplify(boolean simplify) {

        m_GEMS.setSimplify(simplify);
    }

    /**
     * Returns the tip text for this property
     * @return tip text for this property suitable for
     * displaying in the explorer/experimenter gui
     */
    public String elitismTipText() {
        return "Always let the best individual survive to the next generation?";
    }

    /**
     * Get the value of eli.
     *
     * @return Value of eli.
     */
    public boolean getElitism() {

        return m_GEMS.getElitism();
    }

    /**
     * Set the value of eli.
     *
     * @param elitism Value to assign to eli.
     */
    public void setElitism(boolean elitism) {

        m_GEMS.setElitism(elitism);
    }
}
